package com.adtec.base.cloud.xxljobservise.xxljob.xxljob.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

@Component
@Slf4j
public class CheckIpAndPortUtil {

    //测试IP和端口是否通
    public boolean telnetIpAndPort(String hostAddress, int port) {
        Socket socket = new Socket();
        boolean status = false;
        try {
            socket.connect(new InetSocketAddress(hostAddress, port), 3000);
            log.info(hostAddress + ":" + port + "测试成功");
            status = true;
        } catch (IOException e) {
            log.info(hostAddress + ":" + port + "测试失败");
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return status;
    }

    //测试IP是否通
    public boolean pingIp(String hostAddress) {
        //实现ping某个IP的功能
        int timeOut = 3000;  //超时应该在3钞以上
        boolean status = false;
        try {
            status = InetAddress.getByName(hostAddress).isReachable(timeOut);
            log.info("本地 ping IP: " + hostAddress + " 的结果为:" + status);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return status;
    }

    //获取本地IP
    public String getNativeIP() {
        String hostAddress = "";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
            log.info("本机IP地址为:" + hostAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostAddress;
    }
}
